//
//  RBTimerCountDown.m
//  RMMaterialRed
//
//  Created by XBWH on 2024/3/6.
//

#import "RBTimerCountDown.h"

@implementation BlockObject
@synthesize block = _block;
- (id)initWithBlock:(id)block {
    self = [super init];
    if (self) {
        self.block = block;
    }
    return self;
}
- (void)setBlock:(id)block {
    _block = block;
}
+ (BlockObject *)infoWithBlock:(id)block {
    BlockObject *info = [[BlockObject alloc] initWithBlock:block];
    return info;
}
@end
@interface RBTimerInfo : NSObject
@property (strong,nonatomic) BlockObject *chagedBlock;
@property (strong,nonatomic) BlockObject *completeBlock;
@property (nonatomic) float interval;
@property (nonatomic) float time;
@property (nonatomic) float remain;
@property (strong,nonatomic) NSTimer *timer;
+(RBTimerInfo *)rb_timeInfoWithTime:(float)time interval:(float)interval changed:(void(^)(float remain))changed complete:(void(^)(void))complete;
@end
typedef void(^TimerChanged)(float remain);
@implementation RBTimerInfo
@synthesize chagedBlock;
@synthesize completeBlock;
@synthesize interval;
@synthesize time;
@synthesize remain;
@synthesize timer = _timer;
+(RBTimerInfo *)rb_timeInfoWithTime:(float)time interval:(float)interval changed:(void(^)(float remain))changed complete:(void(^)(void))complete {
    RBTimerInfo *info = [[RBTimerInfo alloc] init];
    info.chagedBlock = [BlockObject infoWithBlock:changed];
    info.completeBlock = [BlockObject infoWithBlock:complete];
    info.interval = interval;
    info.time = time;
    info.remain = time;
    return info;
}
- (void)rb_counter:(NSTimer *)timer {
    self.remain -= interval;
    TimerChanged block = self.chagedBlock.block;
    if (block) {
        block(self.remain);
    }
    if (self.remain <= 0 && self.time != 0) {
        if ([timer isValid]) {
            [timer invalidate];
        }
        ((void(^)())self.completeBlock.block)();
    }
}

@end

@implementation RBTimerCountDown
+ (RBTimerCountDown *)rb_timerWithTime:(float)time interval:(float)interval changed:(void(^)(float remain))changed complete:(void(^)(void))complete{
    RBTimerInfo *timeInfo = [RBTimerInfo rb_timeInfoWithTime:time interval:interval changed:changed complete:complete];
    RBTimerCountDown *timer = (RBTimerCountDown *)[NSTimer scheduledTimerWithTimeInterval:interval target:timeInfo selector:@selector(rb_counter:) userInfo:timeInfo repeats:YES];
    return timer;
}

@end
